<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="电站名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入电站名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="添加时间" prop="date">
        <el-date-picker clearable
          v-model="queryParams.date"
          type="date"
          placeholder="请选择添加时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search"  @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:station:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:station:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:station:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:station:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="main">
      <div class="left">
          <el-tree
              :data="stationList"
              :props="{ label: 'name', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              @node-click="handleNodeClick"
              :default-expanded-keys="expandedKeys"
              @node-expand="handleNodeExpand"
              @node-collapse="handleNodeCollapse"/>

      </div>
      <div class="right">
        <!--   电站   -->
        <el-table v-loading="loading" :data="station" @selection-change="handleSelectionChange" v-if="level==1">
          <el-table-column label="电站名称" align="center" prop="name" />
          <el-table-column label="电站地址" align="center" prop="diZhi"/>
          <el-table-column label="装机容量(Kva)" align="center" prop="rongLiang"/>
          <el-table-column label="运行容量(Kva)" align="center" prop="yunXingRongLiang"/>
          <el-table-column label="电压等级" align="center" prop="dianYaDengJi" width="180"/>
          <el-table-column label="CT变比" align="center" prop="ctBianBi" width="180"/>
          <el-table-column label="PT变比" align="center" prop="ptBianBi" />
          <el-table-column label="变压器数量" align="center" prop="byqCount" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="Plus"
                  @click="addGroup(scope.row)"
                  v-hasPermi="['system:group:add']"
              >新增组串</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:station:edit']"
              >修改</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:station:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!--分组 -->
        <el-table v-loading="loading" :data="group" v-if="type=='高压表'||type=='变压器'">
          <el-table-column label="组名称" align="center" prop="name" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="Plus"
                  @click="handleAdd(scope.row)"
                  v-hasPermi="['system:group:add']"
              >添加</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="Edit"
                  @click="updateGroup(scope.row)"
                  v-hasPermi="['system:group:edit']"
              >修改</el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:group:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-table v-loading="loading" :data="biao" v-if="level>2&&(type!='高压表'&&type!='变压器')">
          <el-table-column label="电表名称" align="center" prop="name" />
          <el-table-column label="质保到期" align="center" prop="zhiBaoDaoQi" />
          <el-table-column label="电表编号" align="center" prop="xuLieHao" />
          <el-table-column label="电表类型" align="center" prop="type" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
<!--              <el-button
                  size="mini"
                  type="text"
                  icon="Edit"
                  @click="updateDianBiao(scope.row)"
                  v-hasPermi="['system:group:edit']"
              >修改</el-button>-->
              <el-button
                  size="mini"
                  type="text"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:group:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="fenYe">
      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          @pagination="getList" :pager-count=3
      />
    </div>

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="电站名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入电站名称" />
        </el-form-item>
        <el-form-item label="变压器个数" prop="byqCount">
          <el-input v-model="form.byqCount" placeholder="请输入变压器个数" />
        </el-form-item>
        <el-form-item label="电压等级" prop="dianYaDengJi">
          <el-input v-model="form.dianYaDengJi" placeholder="请输入电压等级" />
        </el-form-item>
        <el-form-item label="ct变比" prop="ctBianBi">
          <el-input v-model="form.ctBianBi" placeholder="请输入ct变比" />
        </el-form-item>
        <el-form-item label="pt变比" prop="ptBianBi">
          <el-input v-model="form.ptBianBi" placeholder="请输入pt变比" />
        </el-form-item>
        <el-form-item label="地址" prop="diZhi">
          <el-input v-model="form.diZhi" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="装机容量" prop="rongLiang">
          <el-input v-model="form.rongLiang" placeholder="请输入装机容量" />
        </el-form-item>
        <el-form-item label="运行容量" prop="yunXingRongLiang">
          <el-input v-model="form.yunXingRongLiang" placeholder="请输入运行容量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" v-model="openGroup" width="500px" append-to-body>
      <el-form ref="groupForm" :model="groupForm" :rules="rulesGroup" label-width="100px">
        <el-form-item label="类别" prop="type">
          <el-select v-model="groupForm.type" @change="groupTypeChange">
            <el-option
                v-for="item in groupTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="组串名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入组串名称" />
        </el-form-item>

        <el-form-item label="SN号" prop="xuLieHao" v-if="gaoYaFlag">
          <el-input v-model="groupForm.xuLieHao" placeholder="请输入SN号" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGroup">确 定</el-button>
        <el-button @click="cancelGroup">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" v-model="openBiao" width="500px" append-to-body>
      <el-form ref="" :model="biaoForm" :rules="rulesBiao" label-width="100px">
        <el-form-item label="SN号" prop="xuLieHao">
          <el-input v-model="biaoForm.xuLieHao" placeholder="请输入SN号" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBiao">确 定</el-button>
        <el-button @click="cancelBiao">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listStation, getStation, delStation, addStation, updateStation } from "@/api/system/station";
import {getGroup, addGroup, updateGroup, delGroup} from "@/api/system/group";
import {getBei, getBeiByGroup, addBei, delBei} from "@/api/system/bei";
export default {
  name: "Station",
  data() {
    return {
      openBiao:false,
      gaoYaFlag:false,
      groupForm:{
        id:null,
        type:null,
        name:null,
        xuLieHao:null,
        stationId:null,
        gaoYaId:null,
      },
      biaoForm:{
        id:null,
        type:null,
        name:null,
        xuLieHao:null,
        groupId:null,
      },
      groupTypes:[
        {
          text:'变压器',
          value:'变压器',
        } ,
        {
          text:'高压表',
          value:'高压表',
        }
      ],
      type:"",
      openGroup:false,
      level:0,
      //默认展开的节点数组
      expandedKeys:[],
      //电站
      station:[],
      //分组
      group:[],
      //电表
      biao:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      stationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: null,
        date: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "电站名称不能为空", trigger: "blur" }
        ],
        byqCount: [
          { required: true, message: "变压器个数不能为空", trigger: "blur" }
        ],
        diZhi: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        rongLiang: [
          { required: true, message: "装机容量不能为空", trigger: "blur" }
        ],
        yunXingRongLiang: [
          { required: true, message: "运行容量不能为空", trigger: "blur" }
        ],
        lng: [
          { required: true, message: "经度不能为空", trigger: "blur" }
        ],
        lat: [
          { required: true, message: "纬度不能为空", trigger: "blur" }
        ],
      },
      rulesGroup:{
        name: [
          { required: true, message: "组串名称不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "组串类型不能为空",trigger: "blur"}
        ]
      },
      rulesBiao:{
        xuLieHao:[
          { required: true, message: "序列号不能为控", trigger: "blur" },
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 展开节点 */
    handleNodeExpand(data){
      let flag=false;
      this.expandedKeys.some(item=>{
        if (item===data.id){//判断当前节点是否在默认展开的数组里，如果存在就不做处理
          flag=true;
          return true;
        }
      })
      if(!flag){
        this.expandedKeys.push(data.id)
      }
    },
    /** 关闭节点 */
    handleNodeCollapse(data){
      //从expandedKeys中删除当前关闭的节点
      this.expandedKeys.some((item,i)=>{
        if(item===data.id){
          this.expandedKeys.splice(i,1)
        }
      })
      this.removeChildrenIds(data)
    },
    removeChildrenIds(data){
      const that=this;
      if(data.children){
        data.children.forEach(function (item){
          const index=that.expandedKeys.indexOf(item.id)
          if(index>0){
            that.expandedKeys.splice(index,1)
          }
          that.removeChildrenIds(item)
        })
      }
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelGroup(){
      this.openGroup=false;
    },
    cancelBiao(){
      this.openBiao=false;
      this.reSetBiao()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        byqCount: null,
        dianYaDengJi: null,
        ctBianBi: null,
        ptBianBi: null,
        diZhi: null,
        rongLiang: null,
        yunXingRongLiang: null,
        lng: null,
        lat: null,
        img0: null,
        img1: null,
        img2: null,
        date: null
      };
      this.resetForm("form");
    },
    reSetGroup() {
      this.groupForm={
        id:null,
        type: null,
        xuLieHao: null,
        name: null,
      }
    },
    reSetBiao(){
      this.biaoForm={
        id:null,
        type:null,
        name:null,
        xuLieHao:null,
        groupId:null,
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      const type=row.type
      if(type=="高压表"){
        this.title = "添加组串";
        this.openGroup=true;
        this.gaoYaFlag=false
        this.reSetGroup();
        this.groupForm.type="变压器"
        this.groupForm.stationId=row.stationId
        this.groupForm.gaoYaId=row.id;
      }else if(type=="变压器"){
        this.openBiao=true
        this.biaoForm.groupId=row.id

      }
      this.reset();
      this.open = true;

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改电站";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              getStation2(this.form.id,this)
              this.getList()
            });
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      const type=row.type;
      const name=row.name
      console.log(row)
      console.log("type: " + type)
      if(type=="无功补偿装置"||type=="进线柜"){
        this.$modal.confirm('是否确认删除"' + name + '"的数据项？').then(function() {
          return delBei(ids)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }else if(type=="高压表"||type=="变压器"){
        this.$modal.confirm('是否确认删除"' + name + '"的数据项？').then(function() {
          return delGroup(ids,type)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      } else{
        this.$modal.confirm('是否确认删除"' + name + '"的数据项？').then(function() {
          return delStation(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 新增 */
    addGroup(row){
      this.reSetGroup()
      this.gaoYaFlag=false
      const stationId=row.id;
      this.groupForm.stationId=stationId
      this.openGroup=true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/station/export', {
        ...this.queryParams
      }, `station_${new Date().getTime()}.xlsx`)
    },
    /**/
    handleNodeClick(data1,data2,data3,data4){
      const level=data2.level
      this.level=level
      if(level>1){
       this.type=data1.type
      }
      if(level==1){
        //电站
        this.type=""
        this.loading = true;
       getStation2(data1.id,this)
      }else if(this.type=="高压表"||this.type=="变压器"){
        //分组
        getGroup(data1.id).then(response=>{
          this.group=[];
          this.group.push(response.data)
        })
      }else {
        //电表
        getBei(data1.id).then(response=>{
          this.biao=[];
          this.biao.push(response.data)
        })
      }
    },
    submitGroup(){
      this.$refs["groupForm"].validate(valid => {
        if (valid) {
          if (this.groupForm.id != null) {
            updateGroup(this.groupForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openGroup = false;
              getGroup(this.groupForm.id).then(response=>{
                this.group=[];
                this.group.push(response.data)
              })
              this.getList()
            });
          } else {
            addGroup(this.groupForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openGroup=false
              this.getList();
            })
          }
        }
      });
    },
    groupTypeChange(e){
      this.groupForm.type=e;
      if(e=="高压表"){
        this.gaoYaFlag=true
      }else {
        this.gaoYaFlag=false
      }
    },
    updateGroup(row){
      this.reSetGroup();
      const id = row.id || this.ids
      this.title = "修改组串";
      getGroup(id).then(response => {
        this.groupForm = response.data;
        const groupId=this.groupForm.id
        if(this.groupForm.type=="高压表"){
          this.gaoYaFlag=true
          getBeiByGroup(groupId).then(response => {
            this.groupForm.xuLieHao=response.data.xuLieHao
          })
        }else{
          this.gaoYaFlag=false
        }
        this.openGroup = true;
      });
    },
    updateDianBiao(row){
      //console.log(row)

    },
    submitBiao(){
      addBei(this.biaoForm).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.openBiao=false
        this.getList();
      })
    }
  }
};
function getStation2(id,_this){
  getStation(id).then(response => {
    _this.station=[];
    _this.station.push(response.data)
    _this.loading = false;
  });
}
</script>
<style>
  .main{
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .left{
    height: 76vh;
    width: 15%;
    overflow-y:auto;
    overflow-x: auto;
    /*position: relative;*/
  }
  .right{
    width: 85%;
  }
  .fenYe{
    bottom: 1%;
    position: absolute;
    left: 16%
  }
</style>
